package com.market.xg.auth.service.ums.impl;

import com.google.common.collect.Maps;
import com.market.xg.auth.dao.ums.mapper.AuthAggMapper;
import com.market.xg.auth.dao.ums.mapper.UmsAdminMapper;
import com.market.xg.auth.dao.ums.po.GetUmsRolePO;
import com.market.xg.auth.dao.ums.po.UmsAdminPO;
import com.market.xg.auth.dao.ums.po.UmsRolePO;
import com.market.xg.auth.service.ums.UmsAdminService;
import com.market.xg.auth.service.ums.dto.LoginInfoReqDTO;
import com.market.xg.common.starter.auth.XgAppUser;
import com.market.xg.common.starter.auth.XgPcUser;
import com.market.xg.common.starter.util.BeanUtils;
import com.market.xg.common.starter.util.JwtUtil;
import com.market.xg.exception.starter.BusinessException;
import com.market.xg.exception.starter.ErrorCode;
import com.market.xg.exception.starter.base.IErrorCode;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Slf4j
@Service
public class UmsAdminServiceImpl implements UmsAdminService {

    @Autowired
    UmsAdminMapper umsAdminMapper;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    AuthAggMapper authAggMapper;

    @Override
    public String getAppToken(LoginInfoReqDTO loginInfoReqDTO) {
        log.info("getAppToken loginInfoReqDTO={}",loginInfoReqDTO);
        try {
            XgAppUser xgAppUser = new XgAppUser();
            GetUmsRolePO getUmsRolePO = BeanUtils.copy(loginInfoReqDTO, GetUmsRolePO.class);
            List<UmsRolePO> umsRolePOList = authAggMapper.selectRoles(getUmsRolePO);
            if (Objects.isNull(umsRolePOList)){
                throw new BusinessException(ErrorCode.TOKEN_GET_ERROR);
            }
            xgAppUser.setUserName(loginInfoReqDTO.getUserName());
            xgAppUser.setRoleNames(umsRolePOList.stream().map(UmsRolePO::getRoleName).collect(Collectors.toList()));
            return jwtUtil.createToken(xgAppUser);
        }catch (Exception e){
            log.error("getAppTokenError",e);
            throw new BusinessException(ErrorCode.TOKEN_GET_ERROR);
        }
    }

}
